package com.example.tamplate.controller;

import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.tamplate.model.Wallpaper;
import com.example.tamplate.model.vo.Result;
import com.example.tamplate.service.CategoryService;
import com.example.tamplate.service.impl.WallpaperServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/wallpaper")
@Api(tags = "壁纸")
public class WallpaperController {

    @Autowired
    public WallpaperServiceImpl wallpaperService;


    @Autowired
    private CategoryService categoryService;


    @ApiOperation("添加")
    @PostMapping("/add")
    public Result addCWallpaper(@Validated @RequestBody Wallpaper wallpaper, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // 获取绑定结果中的字段错误信息
            FieldError fieldError = bindingResult.getFieldError();
            // 获取字段错误信息的错误消息
            String errorMessage = fieldError.getDefaultMessage();
            // 返回验证失败的结果，错误消息为错误提示信息
            return Result.fail(errorMessage);
        } else {
            wallpaperService.save(wallpaper);
            return Result.success(wallpaper);
        }
    }



    @ApiOperation("查询")
    @GetMapping("/list")
    public Result listWallpaper(@RequestParam(required = false) Integer pageNum, @RequestParam(required = false) Integer pageSize) {
        QueryWrapper<Wallpaper> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");

        if (pageNum == null || pageSize == null) {
            List<Wallpaper> wallpaperList = wallpaperService.list(queryWrapper);
            return Result.success(wallpaperList);
        } else {
            Page<Wallpaper> page = new Page<>(pageNum, pageSize);
            Page<Wallpaper> wallpaperPage = wallpaperService.page(page, queryWrapper);
            return Result.success(wallpaperPage);
        }
    }


    @ApiOperation("推荐")
    @GetMapping("/collections")
    public Result listWallpaper() {
        // 获取所有壁纸数据
        List<Wallpaper> allWallpapers = wallpaperService.list();
        // 打乱数据顺序
        Collections.shuffle(allWallpapers);
        // 获取前6条数据
        List<Wallpaper> randomWallpapers = allWallpapers.stream()
                .limit(8)
                .collect(Collectors.toList());

        return Result.success(randomWallpapers);
    }

    @ApiOperation("分类查询")
    @GetMapping("/listByCategory/{categoryId}")
    public Result listWallpaperByCategory(@PathVariable Long categoryId) {
        List<Wallpaper> wallpaperList = wallpaperService.list(new QueryWrapper<Wallpaper>()
                .eq("categoryId", categoryId)
//                .orderByDesc("id")
                .orderByDesc("createTime"));  // 按照创建时间倒序排序
        return Result.success(wallpaperList);
    }



    @ApiOperation("详情")
    @GetMapping("/detail/{id}")
    public Result<Wallpaper> detailWallpaper(@PathVariable Integer id) {
        Wallpaper wallpaper = wallpaperService.getById(id);
        return Result.success(wallpaper);
    }

    @ApiOperation("删除")
    @DeleteMapping("/delete/{id}")
    public Result deleteWallpaper(@PathVariable Integer id) {
        boolean removeById = wallpaperService.removeById(id);
        if (removeById) {
            return Result.success("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }

    @ApiOperation("修改")
    @PutMapping("/update/{id}")
    public Result<Wallpaper> updateWallpaper(@RequestBody Wallpaper wallpaper, @PathVariable Integer id) {
        wallpaper.setId(id);
        boolean updateById = wallpaperService.updateById(wallpaper);
        if (updateById) {
            // 检查是否成功修改了信息
            Wallpaper updatedWallpaper = wallpaperService.getById(id);
            if (updatedWallpaper != null) {
                return Result.success(updatedWallpaper);
            }
        }
        return Result.fail(wallpaper);
    }

}
